﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Collections;

namespace Vnoss.Language.French.DAL
{
    /// <summary>
    /// Gestion de cache pour DAL. Least Recently Used
    /// </summary>
    internal class LruCache
    {
        private int _cacheSize;

        private Hashtable _cache;
        private IList _keyList;
        /// <summary>
        /// Nombre maximum des éléments cachés
        /// </summary>
        public int CacheSize
        {
            get { return _cacheSize; }
        }

        /// <summary>
        /// Constructor 
        /// </summary>
        /// <param name="cacheSize">nombre des élémentss</param>
        public LruCache(int cacheSize)
        {
            _cacheSize = cacheSize;
            _cache = Hashtable.Synchronized(new Hashtable());
            _keyList = ArrayList.Synchronized(new ArrayList());

        }

        /// <summary>
        /// Constructor par défaut
        /// </summary>
        public LruCache() : this(100) { }


        /// <summary>
        /// Accès au cache élément
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object this[object key]
        {
            get
            {
                _keyList.Remove(key);
                _keyList.Add(key);
                return _cache[key];
            }
            set
            {
                _cache[key] = value;
                if (_keyList.Count > _cacheSize)
                {
                    object oldestKey = _keyList[0];
                    _keyList.Remove(oldestKey);
                    _cache.Remove(oldestKey);
                }
            }
        }

        /// <summary>
        /// Clear le cache
        /// </summary>
        public void Clear()
        {
            _keyList.Clear();
            _cache.Clear();

        }

    }
}
